var player1 = new Player($('.c_vs_p_r aside'), true),
	player2 = new Player($('.c_vs_p_l aside'), false),
	boardInfos = null,
	isSilent = true,
	isHomeToBoard = false,

	audio1 = [], // 玩家的击打胜
	audio2 = [], // npc的击打胜
	audioIndex1 = 0, // 玩家击打声的序号
	audioIndex2 = 0, // npc击打胜的序号
	isGameOver = true,

	isBtnLaught = false, //是否嘲笑
	isInterrput = false, // 
	isNpcLaugh = false,
	random = 5, //相隔时长
	intNum = 0, //中断次数
	bypass = 0, //第几次不回头

	player1CurTimer = null, // 玩家 嘲笑的周期
	player2CurTimer = null, // npc 嘲笑的周期

	level = 2, //等级
	hitTime = 320, // npc打的周期
	laughTime = 380, // npc 笑的周期
	num = 60;

//一开始就是需要初始化	
$('#userInfo img').attr('src', myUser.head_img); //排行榜头像
$('#userInfo span').html(myUser.uname); // 排行榜名字

preventWXDefault();

function preventWXDefault() { // 防止下拉 出现 微信背景
	$(window).on('touchmove', function(e) {
		if(!$('.scrollInner')[0].contains(e.target)) {
			e.preventDefault();
			return false;
		}
	})
	$('.box').on('touchmove', function(e) {
		if(!$('.scrollInner')[0].contains(e.target)) {
			e.preventDefault();
			return false;
		}
	})
}

function init() {
	$('.guide').removeClass('hide')
	$('.countDown h2').html(3);
	$('.countDown').addClass('hide');
	num = 60;
	intNum = 0, //中断次数
		$('.clock_num').html(num);
	$('.c_vs_chair_r span').html(0);
	$('.c_vs_chair_l span').html(0);
	isGameOver = true;
	statusToNormal();
	player1.init();
	player2.init();
	startGame();
	isGameOver = false;
	changeClass($('#ctrBtn'), 'click_btn_on');
}

function enterGame() {
	$('.goOut_wrap').addClass('hide');
	$('.countDown').removeClass('hide');
	audioTrigger(audio1, audio2, 10);
	var url = "http://g.sina.cn/aj/yc/xjhys/score?act=get_random_user&gname=xjhys&uid=" + myUser.uid;
	$.ajax({
		url: url,
		type: 'get',
		async: false,
		dataType: 'jsonp',
		jsonp: "callback",
		jsonpCallback: "success_jsonpCallback1",
		success: function(res) {
			var player2 = res.data;
			$('.playerinfo1 img').attr('src', myUser.head_img);
			$('.playerinfo1 span').html(myUser.uname);
			$('.playerinfo2 img').attr('src', player2.head_img);
			$('.playerinfo2 span').html(player2.uname);

			$('.vs_bar strong').eq(0).html(player2.uname); //游戏中的信息
			$('.vs_bar strong').eq(1).html(myUser.uname);
			$('.vs_bar_r_icon img').attr('src', myUser.head_img);
			$('.vs_bar_l_icon img').attr('src', player2.head_img);
			afterSetInfo();
		},
		error: function() {
			console.warn('请求失败');
		}
	})
}

function afterSetInfo() {
	$('.box').eq(1).removeClass('hide').siblings().addClass('hide');
	$('.vs_close').on('touchstart', function() { // 点击取消按钮
		isReadyStart = false;
		$('.box').eq(0).removeClass('hide').siblings().addClass('hide');
	})
	isReadyStart = true;

	var player1Img = new Image(),
		player2Img = new Image(),
		switchOnImg = new Image(),
		switchOffImg = new Image(),
		bossImg = new Image();

		player1Img.src = PATH + '/images/p_l.png';
		player2Img.src = PATH + '/images/p_r.png';
		bossImg.src = PATH + '/images/boss.png';
		switchOnImg.src = PATH + '/images/switchOn.png';
		switchOffImg.src = PATH + '/images/switchOff.png';
	var preImgs = [player1Img, player2Img, bossImg, switchOffImg, switchOnImg];
	
	preLoadImgs(preImgs, function() {
		if(isReadyStart) {
			$('.c_vs_chair_r span').html(0); //初始化分数
			$('.c_vs_chair_l span').html(0);
			$('.box').eq(2).removeClass('hide').siblings().addClass('hide');
			setTimeout(function() {
				$('.box').eq(3).removeClass('hide').siblings().addClass('hide');
				setTimeout(function() {
					restartGame();
				}, 300)
			}, 300)
		}
	})
}

new Audio();

Aduio.src = "../video.mp3";

//获取npc头像等信息
function audioTrigger(audio1, audio2, length) {
	console.log('enter trigger*****');
	for(var i = 0; i < length; i++) {
		audio1[i] = new Audio(PATH + '/mp3/hit.mp3');
		audio2[i] = new Audio(PATH + '/mp3/hit.mp3');
		audio1[i].load();
		audio2[i].load();
	}
	$('#musicLaugh')[0].play();
	$('#goOut')[0].play();
	$('#scream')[0].play();

	setTimeout(function() {
		$('#musicLaugh')[0].pause();
		$('#goOut')[0].pause();
		$('#scream')[0].pause();
	}, 50)
}

//首页的 开始游戏
$('.fight_op_wrap aside').eq(0).on('touchend', function() {
	enterGame();
});

//按钮 再来一局
$('.result_op_wrap aside').eq(0).on('click', function() {
	enterGame();
});
//按钮 分享
$('.result_op_wrap aside').eq(1).on('click', function() {
	$('.wxShare').removeClass('hide');
});

//按钮 查看排行榜
$('.result_more').on('click', function() {
	isHomeToBoard = false;
	getBoard(myUser.uid);
	$('.box').eq(5).removeClass('hide').siblings().addClass('hide');
})
// 首页查看排行榜
$('.home_result_more a').on('click', function() {
	isHomeToBoard = true;
	getBoard(myUser.uid);
	$('.box').eq(5).removeClass('hide').siblings().addClass('hide');
});

//浮层
$('.wxShare').on('touchstart', function() {
	$(this).addClass('hide');
})

//倒计时弹层 是否 开启音乐按钮
$('.remindBox .remind').on('touchstart', function() {
	var flag = $(this).hasClass('switchOn');
	console.log(flag);
	isSilent = flag;
	if(flag) {
		$(this).removeClass('switchOn');
		$(this).addClass('switchOff');
	} else {
		$(this).removeClass('switchOff');
		$(this).addClass('switchOn');
	}
})

//游戏页面 音乐标签
$('.music_wrap').on('touchstart', function() {
	if(!isSilent) {
		$('#goOut')[0].pause();
		$('#musicLaugh')[0].pause();
		$('#scream')[0].pause();
		$('#goOut')[0].currentTime = 0;
		$('#musicLaugh')[0].currentTime = 0;
		$('#scream')[0].currentTime = 0;
	}
	if(isSilent) {
		isSilent = false;
		changeClass($('.music_wrap span'), 'music_icon');
		$(this).removeClass('switchOn'); // 关闭弹层开关
		$(this).addClass('switchOff');
	} else {
		isSilent = true;
		changeClass($('.music_wrap span'), 'music_icon_pause');
		$(this).removeClass('switchOff'); // 打开弹层开关
		$(this).addClass('switchOn');
	}
})
$('#ctrBtn').on('touchstart', function() {
	if(!isBtnLaught) {
		//		$('#music1')[0].currentTime = 0;
		//		$('#music1')[0].play();
		!isSilent && audio1[(audioIndex1++) % 10].play();
		changeClass($(this), 'click_btn_on on');
		player1.hit();
		if(player2.status === 2) {
			player2.hitAndBeaten();
		} else {
			player2.beaten();
		}
	} else {
		!isSilent && $('#musicLaugh')[0].play();
		changeClass($(this), "cry_btn_on on");
		player1.laugh();
	}
	calcScore();
	return false;
})

$('#ctrBtn').on('touchend', function() {
	clearTimeout(player1CurTimer);
	$(this).removeClass('on');
	player1CurTimer = setTimeout(function() {
		if(!isBtnLaught) {
			if(player1.status !== 5) {
				player1.sitDown();
				player2.sitDown();
			}
		} else {
			player1.sitDown();
		}
	}, 90)
})

//电脑嘲笑击打
//laugh();
//hit();

function startGame() {
	//	60s倒计时
	var clockTimer = setInterval(function() {
		if(isGameOver) {
			clearInterval(clockTimer);
			return;
		}
		num -= 1;
		$('.clock_num').html(num);
		num === 57 && $('.guide').addClass('hide');
		if(num == 0) {
			gameOver();
			clearInterval(clockTimer);
		}
	}, 1000);
}

function submitRes(uid, num, nickname, headimg) {
	console.log(uid, num, nickname, headimg);
	var url = "http://g.sina.cn/aj/yc/xjhys/score?act=submit_res&gname=xjhys&uid=" + uid + "&num=" + num + "&nickname=" + nickname + "&headimg=" + headimg;
	$.ajax({
		url: url,
		type: 'get',
		async: false,
		dataType: 'jsonp',
		jsonp: "callback",
		jsonpCallback: "success_jsonpCallback2",
		success: function(res) {
			console.log(res);
		},
		error: function() {
			console.warn('请求失败');
		}
	})
}

//排行榜
function getBoard(uid) {
	var boardList = null;
	var url = "http://g.sina.cn/aj/yc/xjhys/score?act=board&gname=xjhys&uid=" + uid;
	$.ajax({
		url: url,
		type: 'get',
		async: false,
		dataType: 'jsonp',
		jsonp: "callback",
		jsonpCallback: "success_jsonpCallback3",
		success: function(res) {
			boardInfos = res.data;
			boardList = res.data.board;
			boardRender(boardList);
		},
		error: function() {
			console.warn('请求失败');
		}
	})
}

function boardRender(boardList) {
	$('.scrollInner').html(inner);
	var inner = '';
	for(var i = 0; i < boardList.length; i++) { // 名次在30以内的需要特殊处理
		var item = boardList[i];
		if(!boardInfos.user_rank) {
			boardInfos.user_rank = "无";
		} else if(boardInfos.user_rank <= 30) {
			if(item.uid === myUser.uid) {
				boardInfos.user_rank = i + 1;
			}
		}
		var medalType = '';
		if(i > 2) {
			medalType = '"rank">' + (i + 1);
		} else if(i === 0) {
			medalType = '"first">';
		} else if(i === 1) {
			medalType = '"second">';
		} else if(i === 2) {
			medalType = '"third">';
		}
		inner += '<div class="item">' +
			'<div class="topMain">' +
			'<div class=' + medalType + '</div>' +
			'<img src="' + item.head_img + '" class="playersImg">' +
			'<p class="playersName" >' + item.nick_name + '</p>' +
			'<p class="score">' +
			'<span >' + item.rank_num + '</span>分' +
			'</p>' +
			'</div>' +
			'<div class="bottomLine"></div>' +
			'</div>';
	}
	$('.scrollInner').html(inner);
	$('.li_ran strong').html(boardInfos.user_rank);
	$('.li_num strong').html(boardInfos.user_score);
}

$('.box .backBtn').on('touchstart', function() {
	console.log(isHomeToBoard)
	if(isHomeToBoard) { // 如果是从首页进入的排行榜
		$('.box').eq(0).removeClass('hide').siblings().addClass('hide');
	} else {
		$(this).parent('.box').addClass('hide');
		$('.box').eq(4).removeClass('hide');
		$('.box').eq(3).removeClass('hide');
	}
})
//排行榜end

function hit() { // 电脑打人
	if(!isInterrput && player2.status !== 5 && !isGameOver) {
		//		$('#music2')[0].currentTime = 0;
		//		$('#music2')[0].play();

		!isSilent && audio2[(audioIndex2++) % 10].play();
		calcTime();
		player2.hit();
		if(player1.status === 2) {
			player1.hitAndBeaten();
		} else {
			player1.beaten();
		}
		clearTimeout(player2CurTimer);
		player2CurTimer = setTimeout(function() {
			if(!isInterrput) {
				player2.sitDown();
				player1.sitDown();
			}
		}, 50);
		calcScore();
	}
	setTimeout(hit, hitTime);
}

function laugh() { // 电脑嘲笑人
	if(isNpcLaugh && player2.status !== 5 && !isGameOver) {
		!isSilent && $('#musicLaugh')[0].play();
		calcScore();
		calcTime();
		player2.laugh();
		clearTimeout(player2CurTimer);
		player2CurTimer = setTimeout(function() {
			if(player2.status !== 5) {
				player2.sitDown();
			}
		}, hitTime * 0.6);
		calcScore();
	}
	setTimeout(laugh, laughTime);
}

function calcScore() { // 记录嘲笑和达人的分数
	if(player1.status === 2) { // 2为打人的状态
		player1.score++;
	}
	if(player2.status === 2) {
		player2.score++;
	}
	if(player1.status === 1) { // 1为嘲笑
		calcLaugh(player1, player2);
	}
	if(player2.status === 1) {
		calcLaugh(player2, player1);
	}

	$('.c_vs_chair_r span').html(player1.score);
	$('.c_vs_chair_l span').html(player2.score);
}

function calcLaugh(from, to) {
	if(from.status === 1) {
		if(to.score > 1) {
			to.score -= 2;
		} else {
			to.score = 0;
		}
	}
}

function calcTime() { // 根据等级计算 击打和 嘲笑的周期
	if(level === 1) {
		hitTime = getRandomNumber(300, 380);
		laughTime = getRandomNumber(320, 400);
	} else if(level === 2) {
		hitTime = getRandomNumber(250, 330);
		laughTime = getRandomNumber(300, 380);
	} else if(level === 3) {
		hitTime = getRandomNumber(200, 280);
		laughTime = getRandomNumber(280, 360);
	} else if(level === 4) {
		hitTime = getRandomNumber(150, 230);
		laughTime = getRandomNumber(280, 360);
	} else if(level === 5) {
		hitTime = getRandomNumber(100, 180);
		laughTime = getRandomNumber(150, 270);
	}
}

function reduceLevel() {
	var disScore = player2.score - player1.score;
	if(disScore > 30) {
		if(level > 1) {
			level--
		}
	}
}

function getRandomNumber(m, n) {
	var a = Math.random() * (n - m + 1) + m;
	return Math.floor(a);
}

function changeClass(dom, className) {
	dom.removeClass().addClass(className);
}

function statusToNormal() {
	changeClass($('#ctrBtn'), "click_btn_on");
	player1.sitDown();
	player2.sitDown();
	isBtnLaught = false; //是否嘲笑
	isInterrput = false; // 
	isNpcLaugh = false;
}

function gameOver() {
	_wxShareConfig.title = player1.score + "次会议室papapa，快来挑战我吧！";
	window.shareInit();

	$('.result_info>img').attr('src', myUser.head_img);
	$('.box').eq(4).removeClass('hide');
	statusToNormal();
	changeClass($('#ctrBtn'), 'hide');
	isGameOver = true;
	isInterrput = true;
	if(player1.score > player2.score) {
		$('.result_info aside').eq(0).html('你赢了');
		$('.result_info aside').eq(1).html("共得了" + player1.score + "分");
	} else {
		$('.result_info aside').eq(0).html('你输了');
		$('.result_info aside').eq(1).html("共得了" + player1.score + "分");
	}
	if(player1.score > 0) {
		myUser.score = player1.score;
		submitRes(myUser.uid, myUser.score, myUser.uname, myUser.head_img); // 提交分数
	}
}

function restartGame() {
	$('.countDown').removeClass('hide'); //倒计时动画
	$('.time1').on('animationend', function() {
		init();
	})
}

function preLoadImgs(imgs, callback) {
	var preNum = 0;
	for(var i = 0; i < imgs.length; i++) {
		imgs[i].onload = function() {
			console.log(this.src + '加载成功');
			preNum++;
			if(preNum >= imgs.length) {
				callback();
			}
		}
		imgs[i].onerror = function(err) {
			console.warn(imgs[i] + err)
		}
	}
}